package com.dm0858.bianmin.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.chaychan.library.BottomBarItem;
import com.chaychan.library.BottomBarLayout;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.mine.fragment.MineFragment;
import com.dm0858.bianmin.ui.activity.HttpIndustry;
import com.dm0858.bianmin.model.event.TabRefreshCompletedEvent;
import com.dm0858.bianmin.model.event.TabRefreshEvent;
import com.dm0858.bianmin.ui.adapter.MainTabAdapter;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.base.BaseFragment;
import com.dm0858.bianmin.ui.base.BasePresenter;
import com.dm0858.bianmin.ui.fragment.HomeFragment;
import com.dm0858.bianmin.ui.fragment.TransparentFragment;
import com.dm0858.bianmin.utils.CacheUtils;
import com.dm0858.bianmin.utils.UIUtils;
import com.dm0858.uikit.NoScrollViewPager;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import flyn.Eyes;

public class MainActivity extends BaseActivity {
    private static long mPreTime;
    @Bind(R.id.vp_content)
    NoScrollViewPager mVpContent;

    @Bind(R.id.bottom_bar)
    BottomBarLayout mBottomBarLayout;

    ViewGroup.LayoutParams mVideoViewLayoutParams;

    HomeFragment mhomefragment;
    MineFragment mMineFragment;
    private List<Fragment> mFragments;
    private MainTabAdapter mTabAdapter;

    private int[] mStatusColors = new int[]{
            R.color.status_color_red,
            R.color.status_color_red,
            R.color.status_color_red,
            R.color.status_color_red,
    };

    @Bind(R.id.phone)
    RelativeLayout phone;
    @Bind(R.id.information)
    RelativeLayout information;
    @Bind(R.id.customerService)
    RelativeLayout customerService;
    @Bind(R.id.home)
    RelativeLayout home;
    @Bind(R.id.mine)
    RelativeLayout mine;
    @Bind(R.id.oneBtn)
    BottomBarItem oneBtn;
    @Bind(R.id.twoBtn)
    BottomBarItem twoBtn;
    @Bind(R.id.threeBtn)
    BottomBarItem threeBtn;
    @Bind(R.id.fourBtn)
    BottomBarItem fourBtn;
    @Bind(R.id.fiveBtn)
    BottomBarItem fiveBtn;
    BottomBarItem nowBtn;
    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public boolean enableSlideClose() {
        return false;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void initData() {
        nowBtn = fourBtn;

        fourBtn.setStatus(true);
        mFragments = new ArrayList<>(5);


        mFragments.add(new TransparentFragment());
        mFragments.add(new TransparentFragment());
        mFragments.add(new TransparentFragment());

        mhomefragment=new HomeFragment();
        mFragments.add(mhomefragment);

        mMineFragment = new MineFragment();
        mFragments.add(mMineFragment);


        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                nowBtn.setStatus(false);
                nowBtn = oneBtn;
                oneBtn.setStatus(true);

                startActivity(new Intent(MainActivity.this,AgreementActivity.class));
            }
        });
        information.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn.setStatus(false);
                nowBtn = twoBtn;
                twoBtn.setStatus(true);
                doSendSMSTo("13309095565","");

            }
        });
        customerService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                nowBtn.setStatus(false);
                nowBtn = threeBtn;

                threeBtn.setStatus(true);
                //doSendQQ("2388387983");
                call("08314088880");

            }
        });
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn.setStatus(false);
                nowBtn = fourBtn;
                fourBtn.setStatus(true);
                mVpContent.setCurrentItem(3);
            }
        });

        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn.setStatus(false);
                nowBtn = fiveBtn;
                fiveBtn.setStatus(true);
                mVpContent.setCurrentItem(4);
            }
        });


        HttpIndustry industry = new HttpIndustry();
        industry.genParams();
        FinalHttp finalHttp = new FinalHttp();
        finalHttp.post(industry.getFuncName(), industry,
                new AjaxCallBack<Object>() {
                    @Override
                    public void onSuccess(Object t) {
                        super.onSuccess(t);
                        com.dm0858.bianmin.ui.activity.CacheUtils.setIndustry(MainActivity.this,t.toString());
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo,
                                          String strMsg) {
                    }
                });
    }



    @Override
    public void initListener() {
        mTabAdapter = new MainTabAdapter(mFragments, getSupportFragmentManager());

        mVpContent.setAdapter(mTabAdapter);
        mVpContent.setOffscreenPageLimit(mFragments.size());
        mBottomBarLayout.setViewPager(mVpContent);
        mBottomBarLayout.setCurrentItem(3);
        //设置条目点击的监听
        mBottomBarLayout.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            //如果点击了其他条目
            BottomBarItem bottomItem;
            @Override
            public void onItemSelected(BottomBarItem bottomBarItem, int position) {
                setStatusBarColor(position);//设置状态栏颜色
                bottomItem = mBottomBarLayout.getBottomItem(position);
                if(position==0)
                {
                    bottomItem.setIconSelectedResourceId(R.mipmap.tab_call_selected);//更换为原来的图标
                    //  call("08318212072");
                    return;
                }
                if(position==1)
                {
                    bottomItem.setIconSelectedResourceId(R.mipmap.tab_msg_selected);//更换为原来的图标
                    // doSendSMSTo("13309095565","");
                    return;
                }
                if(position==2)
                {
                    bottomItem.setIconSelectedResourceId(R.mipmap.tab_yuyue_selected);//更换为原来的图标
                    // doSendQQ("2388387983");
                    return;
                }
                // JCVideoPlayer.releaseAllVideos();//底部页签切换或者是下拉刷新，释放资源

                if (position == 3) {
                    bottomItem.setIconSelectedResourceId(R.mipmap.tab_home_selected);//更换为原来的图标
                    //如果点击的是首页
                    if (mBottomBarLayout.getCurrentItem() == position) {
                        //如果当前页码和点击的页码一致,进行下拉刷新
                        String channelCode = "";
                        if (position == 3) {
                            // channelCode = ((HomeFragment) mFragments.get(0)).getCurrentChannelCode();//获取到首页当前显示的fragment的频道
                        } else {

                        }
                        // postTabRefreshEvent(bottomBarItem, position, channelCode);//发送下拉刷新的事件
                    }
                    return;
                }
                if (position == 4) {
                    bottomItem.setIconSelectedResourceId(R.mipmap.tab_home_selected);//更换为原来的图标

                }

                cancelTabLoading(bottomItem);//停止旋转动画
            }
        });
    }

    /**
     * 调起qq功能
     *
     */
    public void doSendQQ(String qqstr){
        if(isQQClientAvailable(MainActivity.this)){
//            String url = "mqqwpa://im/chat?chat_type=crm&uin=4008205555&version=1&src_type=web&web_src=http:://wpa.b.qq.com";
            String url="mqqwpa://im/chat?chat_type=wpa&uin="+qqstr;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        }else{
            UIUtils.showToast("您的手机暂未安装QQ客户端");
        }

    }


    //    * 判断qq是否可用
//    * @param context
//    * @return
//            */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 调起系统发短信功能
     * @param phoneNumber
     * @param message
     */
    public void doSendSMSTo(String phoneNumber,String message){
        if(PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)){
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
            intent.putExtra("sms_body", message);
            startActivity(intent);
        }
    }

    /**
     * 调用拨号界面
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void setStatusBarColor(int position) {
        if (position == 3){
            //如果是我的页面，状态栏设置为透明状态栏
            Eyes.translucentStatusBar(MainActivity.this,true);
        }else{
            Eyes.setStatusBarColor(MainActivity.this, com.dm0858.bianmin.utils.UIUtils.getColor(mStatusColors[position]));
        }
    }

    private void postTabRefreshEvent(BottomBarItem bottomBarItem, int position, String channelCode) {
        TabRefreshEvent event = new TabRefreshEvent();
        event.setChannelCode(channelCode);
        event.setBottomBarItem(bottomBarItem);
        event.setHomeTab(position == 0);
        EventBus.getDefault().post(event);//发送下拉刷新事件
    }

    /**
     * 停止首页页签的旋转动画
     */
    private void cancelTabLoading(BottomBarItem bottomItem) {
        Animation animation = bottomItem.getImageView().getAnimation();
        if (animation != null) {
            animation.cancel();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshCompletedEvent(TabRefreshCompletedEvent event) {
        //接收到刷新完成的事件，取消旋转动画，更换底部首页页签图标
        BottomBarItem bottomItem = mBottomBarLayout.getBottomItem(0);

        cancelTabLoading(bottomItem);//停止旋转动画

        bottomItem.setIconSelectedResourceId(R.mipmap.tab_home_selected);//更换成首页原来图标
        bottomItem.setStatus(true);//刷新图标
    }



    @Override
    protected void onStart() {
        super.onStart();
        registerEventBus(MainActivity.this);
        oneBtn.setStatus(false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterEventBus(MainActivity.this);
    }


    @Override
    protected void onPause() {
        super.onPause();

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
                UIUtils.showToast("再按一次，退出应用");
                mPreTime = System.currentTimeMillis();

            }
            else
            {
                finish();
            }
            if (mhomefragment instanceof HomeFragment) {
                ((HomeFragment) mhomefragment).cancleSelect();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        super.onConfigurationChanged(newConfig);
//        int rot = getWindowManager().getDefaultDisplay().getRotation();
//        if(rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270){
//            mVideoViewLayoutParams = mhomefragment.getView().findViewById(R.id.trim_container).getLayoutParams();
//            RelativeLayout.LayoutParams layoutParams =
//                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
//            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
//            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
//            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//            mhomefragment.getView().findViewById(R.id.trim_container).setLayoutParams(layoutParams);
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//
//        }else if(rot == Surface.ROTATION_0){
////            RelativeLayout.LayoutParams lp = new  RelativeLayout.LayoutParams(320,240);
////            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
//            mhomefragment.getView().findViewById(R.id.trim_container).setLayoutParams(mVideoViewLayoutParams);
//        }
//    }
}
